<?php

!defined('IN_SYSTEM') && exit('Access denied');

class commonControlPage {

    protected $view = NULL;
    protected $user = false;
    protected $hp = false;#当前操作有权限

    /**
     * 初始化
     */
    public function __construct() {
        $this->_initialize();
    }

    private function _initialize() {
        // 初始化View
        $this->view = class_view::getInstance();

        // 设置页面INPUT
        $this->view->input_post = json_encode($_POST);
        $this->view->input_get = json_encode($_GET);

        // App和Mod
        $mod = MOD;
        $app = APP;
        $sti = "{$app}_{$mod}";

        // 用户登陆状态判断
        $user = cauthcode(cgetcookie('auth'),'DECODE');
        if ($user) {
            $this->user = json_decode($user,1);
            $detail = $_ENV['db']->fetch("SELECT * FROM admincp_member_detail WHERE `uid` = '{$this->user['uid']}'");
            $this->user = $this->user + $detail;
        }

        // 用户未登录 跳转到登陆页面
        if (!$this->user && !in_array($app,array('auth','common','cart'))) {
            header("Location: ?app=auth&mod=signin");
            exit('Redirecting...');
        }
		
        $check = !in_array($app,array('auth','common','portal','frame'));
        if ($check) 
		{// 如果当前操作需要权限验证
            $node_detail = $_ENV['db']->fetch("SELECT n.node_id,n.name as node_name,m.name as menu_name,m.menu_id,m.parent_id FROM `admincp_node` as n LEFT JOIN `admincp_menu` as m ON n.menu_group_id = m.menu_id WHERE n.app_val = '".APP."' AND n.mod_val ='".MOD."'");
            $menu_detail = $_ENV['db']->fetch("SELECT `name` FROM `admincp_menu` WHERE `menu_id` = '".(int)$node_detail['parent_id']."'");
            $member_check_row = $_ENV['db']->fetch("SELECT * FROM `admincp_member_perm` WHERE `uid` = '{$this->user['uid']}' AND `node_id` = '{$node_detail['node_id']}'");
			if (!in_array($sti,$_ENV['config']['novalidate']) && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) 
			{
                if (!$member_check_row) $this->showMessage("权限不足  操作：{$node_detail['node_name']}",AJAX ? -403 : 'back');
            }
            if ($member_check_row) 
			{
                $this->hp = true;
            }
            $this->view->menu_name = $menu_detail['name'];
            $this->view->menu_group_name = $node_detail['menu_name'];
            $this->view->node_name = $node_detail['node_name'];
        }
        // 当前登录的管理员信息
        $this->view->user = $this->user;
    }

	/**
     * 显示提示信息
     */
    protected function showMessage($message,$url='') 
	{
        if (AJAX) 
		{
            $this->outputJson($url,$message);
        } 
		else 
		{
            exit("<div style='text-align:center;margin:25% 35%;width:auto;vertical-align:middle;padding:10px;border:1px solid skyblue;'><p>{$message}</p>".($url ? ($url=='back' ? '<a href="javascript:history.back(-1);">返回</a>' : "<a href='{$url['0']}'>{$url['1']}</a>") : '')."</div>");
        }
    }
    
	// 套用小模板展示
    protected function showSmallPage($tpl) 
	{
		$this->view->load_tpl = $tpl;
        $this->view->render('admincp/small_layout');
    }
    

    // 更新指定用户的金额
    // Table:admincp_member_detail
    protected function upadteUserPrice($field,$price,$uid='') {
        $_ENV['db']->runSql("UPDATE admincp_member_detail SET `{$field}`={$field}+{$price} WHERE uid = '{$uid}'");
    }

    // load main page
    protected function showMainPage($tpl) {
        $this->view->load_tpl = $tpl;
        $this->view->render('admincp/main_layout');
    }

    // 验证码校验
    protected function verifyCheck($verify_code) {
        $request_verify_code = md5(strtolower(trim($verify_code)));
        $true_verify_code = cgetcookie(md5(FORMHASH.AUTH_KEY));
        return $request_verify_code === $true_verify_code;
    }

    // 空操作
    public function __call($method,$args=array()) {
        if (method_exists($this,'_empty')) {
            $this->_empty();
        } else {
            exit("<div style='text-align:center;margin:25% 35%;width:240px;vertical-align:middle;padding:10px;border:1px solid skyblue;'>Request fail with <strong>".APP.':'.MOD."[{$method}]</strong></div>");
        }
    }

    // 显示验证码
    public function verifyModule() 
	{
        $length = 4;
        $w = 48;
        $h = 25;
        $randcode = '';
        $text = '234678abcdefghjkmnprtuvwxyzABCDEFGHJKLMNPRTUVWXYZ';
        srand((double)microtime()*1000000);
        $im = imagecreate($w,$h);
        $bgColor = imagecolorallocate($im,255,255,255);
        imagefill($im,0,0,$bgColor);
        for ($i=0;$i<$length;$i++) {
            $code = substr($text,mt_rand(0,48),1);
            $j = !$i ? rand(0,4) : $j + 11;
            imagestring($im,5,$j,5,$code,imagecolorallocate($im,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)));
           //imagettftext($im,24,0,$j,25,imagecolorallocate($im,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)),'arial.ttf',$code); 
			
			$randcode .= $code;
        }
        csetcookie(md5(FORMHASH.AUTH_KEY),md5(strtolower($randcode)));
        //干扰
        # 画弧
        //for ($i=0;$i<1;$i++) {
            //imagearc($im,mt_rand(-5,$w),mt_rand(-5,$h),mt_rand(20,300),mt_rand(20,200),55,44,imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
        //}
        #点
        //for ($i=0,$j=$length*25;$i<$j;$i++) {
        //    imagesetpixel($im,mt_rand(0,$w),mt_rand(0,$h),imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
       // }
        header("Content-type: image/gif");
        imagegif($im);
        imagedestroy($im);
    }
	
	
	
	
	


    /**
     * 检测表单提交
     */
    protected function submitcheck() {
        $error = NULL;

        if (FORMHASH != $_REQUEST['formhash']) {
            $error = '授权错误';
        }

        if (!is_null($error)) {
            echo AJAX ? $this->outputJson(0,$error) : $error;
            exit();
        }

        return true;
    }

    protected function outputJson($state,$message,$extra='') {
        
        echo json_encode(array('state' => $state,'message'=>$message,'extra'=>$extra));exit;
    }
    
    // 2011年11月11日 05:47:14
    protected function buildSql($array) 
	{
        $sql = '';
        foreach ($array as $key=>$val) $sql .= "`{$key}`='{$val}',";
        return 'SET '.substr($sql,0,-1);
    }
	
	/**
     * 分页
	 * (1) 表名
	 * (2) id名称
	 * (3) where条件
     */
	protected function PrePage($tableName,$idName,$where,$page,$orderName)
	{
		$sql = "SELECT count({$idName}) as total FROM `{$tableName}` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.http_build_query($_GET),'TPT');
		$this->view->pager = $pager->output();
		return $_ENV['db']->fetchAll("SELECT * FROM `{$tableName}` WHERE {$where} order by {$orderName} LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
	}
	/**
     * 分页
	 * (1) 表名
	 * (2) id名称
	 * (3) where条件
     */
	protected function PrePageByURL($tableName,$idName,$where,$page,$orderName,$url)
	{
		$sql = "SELECT count({$idName}) as total FROM `{$tableName}` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.$url,'tpt');
		$this->view->pager = $pager->output();
		return $_ENV['db']->fetchAll("SELECT * FROM `{$tableName}` WHERE {$where} order by {$orderName} LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
	}
}